package evol;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.ProcessingInstruction;

import func.rank.RankFunction;

import nodes.Node;
import nodes.visitor.XMLNodeVisitor;

public class XMLOutputter implements TreeOutputter {

	private XMLNodeVisitor v = new XMLNodeVisitor();
	private String dir;
	private String file = "Generation";
	private int gen = 1;
	private org.jdom.output.XMLOutputter outputter = new
		org.jdom.output.XMLOutputter();

	public XMLOutputter(String dirName) {
		this.dir = dirName;
	}
	
	@Override
	public <T> void output(ArrayList<Node<T>> population, RankFunction<T> rank) {
		Element root = new Element("forest");
		root.setAttribute("generation", "" + gen);
		Document doc = new Document();
		ProcessingInstruction pi = new ProcessingInstruction("xml-stylesheet", 
			"type=\"text/xsl\" href=\"tree.xsl\"");
		doc.addContent(pi);
		doc.setRootElement(root);
		
		for(int i = 0; i < population.size(); i++) {
			Node<T> node = population.get(i);
			node.accept(v);
			
			Element tree = v.getRoot();
			tree.setAttribute("score", "" + rank.applyScoreFunction(node));
			tree.setAttribute("place", "" + i);
			root.addContent(tree);
			
			v.reset();
		}
		
		String path = dir + "/" + file + "_" + gen + ".xml";
		FileWriter writer = null;
		gen++;
		
		try {
			writer = new FileWriter(path);
			outputter.output(doc, writer);
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				if(writer != null)
					writer.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
